#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QVBoxLayout>
#include <QLineEdit>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QScrollArea>
#include <QString>
#include <QComboBox>
#include <QFontMetrics>
#include <QSpacerItem>
#include <QPainter>
#include <QDebug>
#include <QTranslator>
#include <QLibraryInfo>
#include <QSettings>
#include <QCheckBox>
#include <QMessageBox>
#include <QCloseEvent>
    SettingsWidget::SettingsWidget(QWidget *parent,GSettings *m_settings):QWidget(parent),m_settings(m_settings)
    {
        QVBoxLayout *mainLayout = new QVBoxLayout(this);
        mainLayout->setContentsMargins(20,20,20,20);//设置边距
        mainLayout->setSpacing(10);
        screen_settings = g_settings_new("org.ukui.screensaver");
        process_settings = g_settings_new("org.ukui.process-manager");
        //标题1设置字体加粗
        QLabel *titleLabel1= new QLabel(tr("General"));

        titleLabel1->setStyleSheet("font-size:14px; font-weight:hold");
        titleLabel1->setContentsMargins(15,0,15,0);//设置边距
        titleLabel1->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
        m_labels["General"] = titleLabel1;
        mainLayout->addWidget(titleLabel1);
        //添加两个有按钮的设置
        addSetItem(mainLayout,tr("Require password when suspend/hibernate"),"sleep-activation-enabled",screen_settings);//这个键值在org.ukui.screensaver
        addSetItem(mainLayout,tr("Password required when waking up the screen"),"close-activation-enabled",screen_settings);//这个键值在org.ukui.screensaver
        //添加带有下拉菜单的部分
        //addSetCombo(mainLayout,tr("Press the power button"), {"interactive","shutdown","suspend","hibernate"},"button-power",false);
        addSetCombo(mainLayout,tr("Press the power button"), {tr("interactive"),tr("shutdown"),tr("suspend"),tr("hibernate")},"button-power",false);//字符串
        addSetCombo(mainLayout,tr("Time to close display"), {tr("Never"),tr("2h"),tr("1h"),tr("30min"),tr("15min"),tr("10min"),tr("5min"),tr("1min")},"sleep-display-ac",true);//int 具体的值
        addSetCombo(mainLayout,tr("Time to sleep"),{tr("Never"),tr("2h"),tr("1h"),tr("30min")},"sleep-computer-ac",true);//int 具体的值
        addSetCombo(mainLayout,tr("Notebook cover"),{tr("hibernate"),tr("suspend"),tr("shutdown"),tr("blank"),tr("nothing")},"button-lid-ac",false);//string
        addSetItem(mainLayout,tr("Dynamic resource scheduling"),"resource-limit-enable",process_settings);//这个键值 在 org.ukui.process-manager

        //电源计划
        QLabel *titleLabel2 = new QLabel(tr("Battery saving plan"));

        titleLabel2->setStyleSheet("font-size:14px; font-weight:hold");
        titleLabel2->setContentsMargins(15,0,15,0);//设置边距
        titleLabel2->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
        m_labels["Battery saving plan"]=titleLabel2;
        mainLayout->addWidget(titleLabel2);

        addSetCombo(mainLayout,tr("Using power"), {tr("Performance"),tr("Energy Efficiency"),tr("Balance")},"power-policy-ac",true);//int 位次
        addSetCombo(mainLayout,tr("Using battery"), {tr("Performance"),tr("Energy Efficiency"),tr("Balance")},"power-policy-battery",true);//int 位次

        //电池节能计划
        QLabel *titleLabel3 = new QLabel(tr("Seltect Powerplan"));

        titleLabel3->setStyleSheet("font-size:14px; font-weight:hold");
        titleLabel3->setContentsMargins(15,0,15,0);//设置边距
        titleLabel3->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

        mainLayout->setSpacing(0);
        m_labels["Seltect Powerplan"]=titleLabel3;
        mainLayout->addWidget(titleLabel3);


        addSetdoubleCombo(mainLayout);
        addSetCombo(mainLayout,tr("Low battery notification"), {tr("40%"),tr("30%"),tr("20%"),tr("10%")},"percentage-low",true);//int 数值不带百分号
        addSetItem(mainLayout,tr("Automatically run saving mode when low battery"),"low-battery-auto-save",m_settings);//这是int类型，需要转成bool型


        const char *keys1[]={"button-power","sleep-display-ac","sleep-computer-ac",
                            "button-lid-ac","power-policy-ac","percentage-action","low-battery-auto-save",
                            "power-policy-battery","percentage-low","action-critical-battery",nullptr};
        const char *keys2[]={"sleep-activation-enabled","close-activation-enabled",nullptr};//org.ukui.screensaver
        const char *keys3[]={"resource-limit-enable",nullptr};

        for(int i = 0; keys1[i]!=nullptr;i++)
        {
            QString fullSignalName = "changed::" + QString(keys1[i]);
            g_signal_connect(m_settings,fullSignalName.toUtf8().constData(),//具体键值
                             G_CALLBACK(settingsChangedCallBack),this);
        }
        for(int i = 0; keys2[i]!=nullptr;i++)
        {    QString fullSignalName = "changed::" + QString(keys2[i]);
             g_signal_connect(screen_settings,fullSignalName.toUtf8().constData(),//具体键值
                             G_CALLBACK(settingsChangedCallBack),this);
        }
        for(int i = 0; keys3[i]!=nullptr;i++)
        {    QString fullSignalName = "changed::" + QString(keys3[i]);
             g_signal_connect(process_settings,fullSignalName.toUtf8().constData(),//具体键值
                             G_CALLBACK(settingsChangedCallBack),this);
        }
        mainLayout->addStretch();//添加伸缩空间，自动调节
        setStyleSheet("background-color:#f0f0f0;");

    }
//
    void SettingsWidget::addSetItem(QVBoxLayout *layout, const QString &text,const QString &gsettings_key,GSettings *settings)
    {
        QFrame *itemFrame =new QFrame();
        itemFrame->setStyleSheet("background-color: white");
        itemFrame->setFixedHeight(40);
        //水平布局
        QHBoxLayout *itemLayout = new QHBoxLayout(itemFrame);
        itemLayout->setContentsMargins(15,0,15,0);
        itemLayout->setSpacing(0);
        //文本标签
        QLabel *textLabel =new QLabel(tr(text.toUtf8().constData()));
        textLabel->setStyleSheet("font-size:14px;color:#333333;");
        //按钮
        QPushButton *slideButton = new QPushButton();
        slideButton->setCheckable(true);
        slideButton->setFixedSize(50,30);
        //slideButton->setStyleSheet("QPushButton {border-radius: 15px; background-color: #e0e0e0;}"
                                  // "QPushButton:checked{background-color:#87CEEB}");
        slideButton->setCursor(Qt::PointingHandCursor);
        slideButton->setStyleSheet(
                    "QPushButton {"
                    "  border: none;"
                    "  border-radius: 15px;"
                    "  background-color: #e0e0e0;"
                    "  padding: 0px;"
                    "}"
                    "QPushButton:checked {"
                    "  background-color: #87CEEB;"
                    "}"
                    "QPushButton::before {"
                    "  content: '';"
                    "}"
                    "QPushButton::after {"
                    "  content: '';"
                    "}"
                    "QPushButton::indicator { width:0; height:0; }"
                    "QPushButton::checked { }"
                    "QPushButton::unchecked { }"
                );

                // 使用事件过滤器自定义绘制滑块小圆点
                class SlideButtonEventFilter : public QObject {
                public:
                    QPushButton *btn;
                    SlideButtonEventFilter(QPushButton *b) : btn(b) {}
                protected://重写eventFilter，只处理Paint事件
                    bool eventFilter(QObject *obj, QEvent *event) override {
                        if (event->type() == QEvent::Paint) {//自定义绘制逻辑
                            QStyleOptionButton opt;
                            opt.initFrom(btn);
                            QPainter p(btn);
                            // 背景
                            QColor bg = btn->isChecked() ? QColor("#87CEEB") : QColor("#e0e0e0");
                            p.setRenderHint(QPainter::Antialiasing);//抗锯齿
                            p.setBrush(bg);//画刷颜色
                            p.setPen(Qt::NoPen);//无边框
                            p.drawRoundedRect(btn->rect(), 15, 15);//绘制圆角矩形
                            // 小圆
                            int margin = 3;
                            int d = btn->height() - 2*margin;
                            int x = btn->isChecked() ? btn->width() - d - margin : margin;
                            QRect circleRect(x, margin, d, d);
                            p.setBrush(Qt::white);
                            p.drawEllipse(circleRect);//绘制原点
                            return true;//事件已处理 ，不在继续传递
                        }
                        return QObject::eventFilter(obj, event);
                    }
                };
        slideButton->installEventFilter(new SlideButtonEventFilter(slideButton));//安装过滤器
        m_slideButtons[gsettings_key]=slideButton;
        // 从 GSettings 加载初始状态 这个按钮的值是布尔值
        // bool enabled = g_settings_get_boolean(settings, gsettings_key.toUtf8().constData());
        // slideButton->setChecked(enabled);
        // qDebug()<<"button 的状态"<< enabled;      
        // // 绑定信号，后续可以加上错误判断
        // connect(slideButton, &QPushButton::toggled, [this, gsettings_key,settings](bool checked) {
        //     qDebug() << "按钮状态变化:" << checked;
        //     g_settings_set_boolean(settings, gsettings_key.toUtf8().constData(), checked);
        // });
        bool enabled;
        if (gsettings_key == "low-battery-auto-save") {
        // 特殊处理：将整数0/1转换为bool
            gint intValue = g_settings_get_int(settings, gsettings_key.toUtf8().constData());
            enabled = (intValue != 0);
            qDebug() << "low-battery-auto-save 初始值:" << intValue << "转换为:" << enabled;
        } else {
        // 正常处理布尔值
            enabled = g_settings_get_boolean(settings, gsettings_key.toUtf8().constData());
        }
        slideButton->setChecked(enabled);
        qDebug() << "按钮初始状态:" << enabled;
        // 绑定信号
        connect(slideButton, &QPushButton::toggled, [this, gsettings_key, settings](bool checked) {
            qDebug() << "按钮状态变化:" << checked;
            if (gsettings_key == "low-battery-auto-save") {
            // 特殊处理：将bool转换为整数0/1
                gint intValue = checked ? 1 : 0;
                g_settings_set_int(settings, gsettings_key.toUtf8().constData(), intValue);
            } else {
            // 正常处理布尔值
                g_settings_set_boolean(settings, gsettings_key.toUtf8().constData(), checked);
            }
        });
        //添加到布局
        m_labels[text]=textLabel;
        itemLayout->addWidget(textLabel);
        itemLayout->addStretch();//伸缩空间，自动调节
        itemLayout->addWidget(slideButton);
        //添加到主布局

        layout->addWidget(itemFrame);
        //layout->addSpacing(0);
    }
    void SettingsWidget ::addSetCombo(QVBoxLayout *layout, const QString &text, const QStringList &items, const QString &gsettings_key, bool isIntType)
    {
        QFrame *itemFrame =new QFrame();
        itemFrame->setStyleSheet("background-color: white");
        itemFrame->setFixedHeight(36);
        //水平布局
        QHBoxLayout *itemLayout = new QHBoxLayout(itemFrame);
        itemLayout->setContentsMargins(15,0,15,0);
        itemLayout->setSpacing(0);
        QLabel *textLabel =new QLabel(tr(text.toUtf8().constData()));
        textLabel->setStyleSheet("font-size:14px;color:#333333;");
        QComboBox *comboBox = new QComboBox();

        // QStringList translatedItems;
        // for (const QString &item : items) {
        //      translatedItems << tr(item.toUtf8().constData()); // 为每个选项添加tr()
        // }
        // comboBox->addItems(translatedItems);

        comboBox->addItems(items);
        comboBox->setCurrentIndex(0);
        //comboBox->setEditable(true);
        
        comboBox->setStyleSheet("QComboBox{padding: 5px; min-width:100px;background-color:white; border-radius:5; border: 1px solid #ccc;}"
                                "QComboBox::drop-down{subcontrol-origin: padding; subcontrol-position: right center; width: 20px;}"
                                "QComboBox QAbstractItemView {border: 1px solid #ccc;background: white;selection-background-color: #0078d7;selection-color:white;}"
                                "QComboBox QAbstractItemView::item:hover{background-color:#e5f1fb;}");
        comboBox->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding);
        m_comboBoxes[gsettings_key]=comboBox;
        m_combos[text]=comboBox;
        // 从 GSettings 加载初始值
        if(isIntType)
        {
            gint current_val = g_settings_get_int(m_settings, gsettings_key.toUtf8().constData());
            qDebug()<<"下拉框get内容"<<current_val;
            
            QString current_text;
            if (gsettings_key == "percentage-low") {
                current_text = QString::number(current_val) + "%";
            } else {
                QString current_str = QString::number(current_val);
                current_text = enumToText(current_str); 
            }
            int index = comboBox->findText(current_text);
            if(index>=0){
                comboBox->setCurrentIndex(index);
            }else {
                comboBox->setCurrentText(0);
            }
            // QString current_str = QString::number(current_val);

            // if (items.contains(current_str)) {
            //     comboBox->setCurrentText(current_str);
            // }
        }
        else{
            gchar *current_tr = g_settings_get_string(m_settings, gsettings_key.toUtf8().constData());
            QString current = QString::fromUtf8(current_tr);
            qDebug()<<"下拉框得到的字符串"<<current;
            g_free(current_tr);
            QString translatedCurrent = enumToText(current); // 例如 "nothing" -> "无操作"
            qDebug()<<"对应的字符串"<<translatedCurrent;
            int index = comboBox->findText(translatedCurrent);
            //int index = comboBox->findText(current);
            qDebug()<<"对应的位次"<<index;
            if (index >= 0) {
                comboBox->setCurrentIndex(index);
            }else{
                qWarning() << "未找到匹配的选项:" << current;
            }
        }
        // 绑定信号
        connect(comboBox, &QComboBox::currentTextChanged, [this, gsettings_key,isIntType](const QString &text) {
            if (isIntType) {
            // int类型需要转换
                if(gsettings_key == "percentage-low")
                {
                    QString value = text;
                    value.remove('%');
                    bool ok;
                    int intValue = value.toInt(&ok);
                    qDebug()<<"点击按钮得到的值"<<value;
                    if (ok) {
                            g_settings_set_int(m_settings, gsettings_key.toUtf8().constData(), intValue);
                        }
                }
                else {
                    int intValue = textToInt(text);
                    qDebug()<<"点击按钮得到的值"<<text;
                    if (intValue>-1) {
                    g_settings_set_int(m_settings, gsettings_key.toUtf8().constData(), intValue);
                    } else {
                        qWarning() << "Invalid integer value for key" << gsettings_key;
                    }
                }
            } else {
            // string类型直接写入
                QString validValue = textToValidEnum(text);
                qDebug()<<"点击按钮得到的值"<<validValue;
                g_settings_set_string(m_settings, gsettings_key.toUtf8().constData(), 
                                validValue.toUtf8().constData());
            }
        });

        itemLayout->addWidget(textLabel);
        m_labels[text]=textLabel;
        itemLayout->addStretch();
        itemLayout->addWidget(comboBox);
        layout->addWidget(itemFrame);
        //layout->addSpacing(0);
    }
    void SettingsWidget ::addSetdoubleCombo(QVBoxLayout *layout)
    {
        QFrame *itemFrame =new QFrame();
        itemFrame->setStyleSheet("background-color: white");
        itemFrame->setFixedHeight(40);
        //水平布局
        QHBoxLayout *itemLayout = new QHBoxLayout(itemFrame);
        itemLayout->setContentsMargins(15,0,15,0);
        itemLayout->setSpacing(0);
        QLabel *textLabel1 =new QLabel(tr("Battery level is lower than"));
        textLabel1->setStyleSheet("font-size:14px;color:black");
        QComboBox *comboBox1 = new QComboBox();
        QStringList items={"5%","6%"};
        comboBox1->addItems(items);
        comboBox1->setCurrentIndex(0);
        comboBox1->setEditable(true);

        comboBox1->setStyleSheet("QComboBox{padding: 5px;combobox-popup: 0; min-width:100px;background-color:white; border-radius:5; border: 1px solid #ccc;}"
                                "QComboBox::drop-down{subcontrol-origin: padding; subcontrol-position: right center; width: 20px;}"
                                "QComboBox QAbstractItemView {border: 1px solid #ccc;background: white;selection-background-color: #0078d7;selection-color:white;}"
                                "QComboBox QAbstractItemView::item:hover{background-color:#e5f1fb;}");

        QLabel *textLabel2 =new QLabel(tr("Run"));
        textLabel2->setStyleSheet("font-size:14px;color:black");
        QComboBox *comboBox2 = new QComboBox();
        comboBox2->addItems({tr("Hibernate"),tr("Suspend"),tr("shutdown"),tr("blank"),tr("nothing")});
        comboBox2->setCurrentIndex(1);
        comboBox2->setEditable(true);
        //comboBox2->setContentsMargins(500,0,10,0);
        comboBox2->setStyleSheet("QComboBox{padding: 5px;combobox-popup: 0; min-width:100px;background-color:white; border-radius:5; border: 1px solid #ccc;}"
                                "QComboBox::drop-down{subcontrol-origin: padding; subcontrol-position: right center; width: 20px;}"
                                "QComboBox QAbstractItemView {border: 1px solid #ccc;background: white;selection-background-color: #0078d7;selection-color:white;}"
                                "QComboBox QAbstractItemView::item:hover{background-color:#e5f1fb;}");


        QString key1 = "percentage-action";
        m_comboBoxes[key1]=comboBox1;
        m_combos["Battery level is lower than"]=comboBox1;
        gint percent = g_settings_get_int(m_settings,key1.toUtf8().constData());
        qDebug()<<"电量低于"<<percent;
        //QString percentStr = QString::number(percent) + "%";
        //int percentindex = comboBox1->findText(percentStr);
        //comboBox1->setCurrentIndex(percentindex);
        //comboBox1->setCurrentText(current_str);
        QString current_str = QString::number(percent);
        if (items.contains(current_str)) {
            comboBox1->setCurrentText(current_str);
        }
        QString key2 = "action-critical-battery";
        m_comboBoxes[key2]=comboBox2;
        m_combos["Run"]=comboBox2;
        QString action = g_settings_get_string(m_settings,key2.toUtf8().constData());
        QString actionText = enumToText(action);
        int actionindex = comboBox1->findText(actionText);
        comboBox2->setCurrentIndex(actionindex);
        qDebug()<<"执行的操作"<<action;
        connect(comboBox1, &QComboBox::currentTextChanged, [this](const QString &text) {
            QString value = text;
            value.remove('%');
            bool ok;
            int intValue = value.toInt(&ok);
            qDebug()<<"点击按钮得到的值"<<intValue;
            if (ok) {
                        g_settings_set_int(this->m_settings, "percentage-action", intValue);
                    }
        });
        connect(comboBox2, &QComboBox::currentTextChanged, [this] (const QString &text){
            QString validValue = textToValidEnum(text);
            qDebug()<<"点击按钮得到的值"<<validValue;
            g_settings_set_string(this->m_settings,"action-critical-battery",validValue.toUtf8().constData());
        });
        itemLayout->addWidget(textLabel1);
        m_labels["Battery level is lower than"]=textLabel1;
        itemLayout->addWidget(comboBox1);
        m_labels["Run"]=textLabel2;
        itemLayout->addWidget(textLabel2);
        // 先添加固定间距，再保留弹性空间
        itemLayout->addSpacing(10);  // 基础间距
        itemLayout->addSpacerItem(
            new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum)
        );  // 设置弹簧
        itemLayout->addStretch();
        itemLayout->addWidget(comboBox2);
        //itemLayout->setSpacing(10);
        layout->addWidget(itemFrame);
    }
    void SettingsWidget::settingsChangedCallBack(GSettings *settings, gchar *key, gpointer user_data)
    {
        SettingsWidget* widget = static_cast<SettingsWidget*>(user_data);
        QMetaObject::invokeMethod(widget,"onSettingChanged",Qt::QueuedConnection,Q_ARG(QString,QString::fromUtf8(key)));
    }

    void SettingsWidget::onSettingChanged(const QString &key)
    {
        qDebug()<<"变化的键值"<<key;
        if(m_slideButtons.contains(key))
        {
            updateSlideButton(key);
        }
        else if(m_comboBoxes.contains(key))
        {
            updateComboBox(key);
        }else if(key == "percentage-action" || key == "action-critical-battery")
        {
            updateComboBox(key);
        }
    }
    void SettingsWidget::updateSlideButton(const QString &key)
    {
        QPushButton *button = m_slideButtons.value(key);
        if(!button) return;
        bool checked;
        if(key == "low-battery-auto-save")
        {
            gint intValue = g_settings_get_int(m_settings, key.toUtf8().constData());
            checked = (intValue != 0);
        }else if(key == "sleep-activation-enabled" || key == "close-activation-enabled"){
            checked = g_settings_get_boolean(screen_settings,key.toUtf8());
        }
        else if(key == "resource-limit-enable"){
            checked = g_settings_get_boolean(process_settings,key.toUtf8());
        }
        qDebug()<<"变化的值为："<<checked;
        //防止信号循环
        button->blockSignals(true);
        button->setChecked(checked);
        button->blockSignals(false);
    }
    void SettingsWidget::updateComboBox(const QString &key)
    {
        QComboBox * combo = m_comboBoxes.value(key);
        if(!combo) return;
        bool isIntType = (key == "sleep-display-ac" || key == "sleep-computer-ac" ||
                          key == "power-policy-ac" || key == "power-policy-battery" ||
                          key == "percentage-low" || key == "percentage-action");
       combo->blockSignals(true);

       if(isIntType){//处理int类型
           gint value = g_settings_get_int(m_settings,key.toUtf8());
           qDebug()<<"updateComboBox变化的"<<value;
           if(key == "percentage-low" || key == "percentage-action"){
               combo->setCurrentText(QString::number(value)+"%");
           }else{
               for(int i=0;i<combo->count();i++)
               {
                   if(textToInt(combo->itemText(i)) == value){
                       qDebug()<<"输出一下找到的文本"<<combo->itemText(i)<<i;
                       combo->setCurrentIndex(i);
                       break;
                   }
               }
           }
       }else{
           gchar *str =g_settings_get_string(m_settings, key.toUtf8().constData());
           QString value = QString::fromUtf8(str);
           g_free(str);

           for(int i=0;i<combo->count();i++)
           {
            //    if(textToValidEnum(combo->itemText(i)) == value){
            //        combo->setCurrentIndex(i);
            //        break;
            //    }
                QString comboText = combo->itemText(i);
                QString enumValue = textToValidEnum(comboText);
                qDebug()<<"comboText"<<comboText<<"enumValue"<<enumValue;
                if(enumValue == value){  // 正确比较转换后的值
                    combo->setCurrentIndex(i);
                    break;
                }
           }
       }
       combo->blockSignals(false);

    }
void SettingsWidget :: retranslateUi(){
    for(auto it = m_labels.begin();it!=m_labels.end();++it){
        it.value()->setText(tr(it.key().toUtf8().constData()));
    }
    //搜索框

    for(auto it = m_combos.begin();it!=m_combos.end();++it)
    {
        QComboBox* combo = it.value();
        int currentIndex = combo->currentIndex();
        combo->blockSignals(true);
        combo->clear();
        if(it.key()=="Press the power button"){
            combo->addItems({tr("interactive"),tr("shutdown"),tr("suspend"),tr("hibernate")});
        }else if(it.key()=="Time to close display"){
            combo->addItems({tr("Never"),tr("2h"),tr("1h"),tr("30min"),tr("15min"),tr("10min"),tr("5min"),tr("1min")});
        }else if(it.key()=="Time to close display"){
            combo->addItems({tr("Never"),tr("2h"),tr("1h"),tr("30min"),tr("15min"),tr("10min"),tr("5min"),tr("1min")});
        }else if(it.key()=="Time to sleep"){
            combo->addItems({tr("Never"),tr("2h"),tr("1h"),tr("30min")});
        }else if(it.key()=="Notebook cover"){
            combo->addItems({tr("hibernate"),tr("suspend"),tr("shutdown"),tr("blank"),tr("nothing")});
        }else if(it.key()=="Using power"){
            combo->addItems({tr("Performance"),tr("Energy Efficiency"),tr("Balance")});
        }else if(it.key()=="Using battery"){
            combo->addItems({tr("Performance"),tr("Energy Efficiency"),tr("Balance")});
        }else if(it.key()=="Low battery notification"){
            combo->addItems({tr("40%"),tr("30%"),tr("20%"),tr("10%")});
        }else if(it.key()=="Battery level is lower than"){
            combo->addItems({tr("5%"),tr("6%")});
        }else if(it.key()=="Run"){
            combo->addItems({tr("Hibernate"),tr("Suspend"),tr("shutdown"),tr("blank"),tr("nothing")});}

        combo->setCurrentIndex(currentIndex);

        combo->blockSignals(false);
    }
}
void SettingsWidget::changeEvent(QEvent *event){
    if(event->type() == QEvent::LanguageChange){
        retranslateUi();
    }
    QWidget::changeEvent(event);
}

int SettingsWidget ::textToInt(const QString &text){
    if (text == "1min"||text == "1分钟") return 60;
    if (text == "5min"||text == "5分钟") return 300;
    if (text == "10min" || text == "10分钟") return 600;
    if (text == "15min" || text == "15分钟") return 900;
    if (text == "30min"|| text == "30分钟") return 1800;
    if (text == "1h"|| text == "1 小时") return 3600;
    if (text == "2h"|| text == "2 小时") return 7200;
    if (text == "3h"|| text == "3 小时") return 10800;
    if(text == "Performance" || text == "最佳性能") return 0;
    if(text == "Energy Efficiency" || text == "最佳能效") return 2;
    if(text == "Balance" || text == "平衡") return 1;
    if(text == "Never" || text == "从不") return -1;
}
QString SettingsWidget ::textToValidEnum(const QString &text){
    // if(text == "询问") return "interactive";
    // if(text == "关机") return  "shutdown";
    // if(text == "睡眠") return "suspend";
    // if(text == "休眠") return "hibernate";
    // if(text == "关闭显示器") return "blank";
    // if(text == "无操作") return "nothing";
    // if(text == "最佳性能") return "performance";
    // if(text == "最佳能效") return "energy efficiency";
    // if(text == "平衡") return "balance";
    // if(text == "从不") return "never";
     if (text == tr("询问") || text == "询问") return "interactive";
    if (text == tr("关机") || text == "关机") return "shutdown";
    if (text == tr("睡眠") || text == "睡眠") return "suspend";
    if (text == tr("休眠") || text == "休眠") return "hibernate";
    if (text == tr("关闭显示器") || text == "关闭显示器") return "blank";
    if (text == tr("无操作") || text == "无操作") return "nothing";
    if (text == tr("最佳性能") || text == "最佳性能") return "performance";
    if (text == tr("最佳能效") || text == "最佳能效") return "energy-efficiency";
    if (text == tr("平衡") || text == "平衡") return "balance";
    if (text == tr("从不") || text == "从不") return "never";
    
    // 添加时间数值映射
    if (text == tr("1min") || text == "1min") return "60";
    if (text == tr("5min") || text == "5min") return "300";
    if (text == tr("10min") || text == "10min") return "600";
    if (text == tr("15min") || text == "15min") return "900";
    if (text == tr("30min") || text == "30min") return "1800";
    if (text == tr("1h") || text == "1h") return "3600";
    if (text == tr("2h") || text == "2h") return "7200";
    if (text == tr("Never") || text == "Never") return "-1";
    if (text == tr("3h") || text == "3h") return "10800";
    return text;
}
QString SettingsWidget ::enumToText(const QString &text){
    if(text == "interactive") return "询问";
    if(text == "shutdown") return  "关机";
    if(text == "suspend") return "睡眠";
    if(text == "hibernate") return "休眠";
    if(text == "blank") return "关闭显示器";
    if(text == "nothing") return "无操作";
    if(text == "performance") return "最佳性能";
    if(text == "energy-efficiency") return "最佳能效";
    if(text == "balance") return "平衡";
    if(text == "never") return "从不";
    if(text == "performance") return "最佳性能";
    if(text == "energy Efficiency") return "最佳能效";
    if(text == "balance") return "平衡";
    if (text == "60") return tr("1min");
    if (text == "300") return tr("5min");
    if (text == "600") return tr("10min");
    if (text == "900") return tr("15min");
    if (text == "1800") return tr("30min");
    if (text == "3600") return tr("1h");
    if (text == "7200") return tr("2h");
    if (text == "10800") return tr("3h");
    if (text == "-1") return tr("Never");
    return text;
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //appTranslator = new QTranslator(this);
    //qtTranslator = new QTranslator(this);
    //根据系统语言来设置默认翻译
    QTranslator *translator = new QTranslator(this);
    translator->load("/home/ky/桌面/zhaowei/powersettings/translations/" + QLocale::system().name());
    QApplication::installTranslator(translator);

    powerTray = new PowerTray(this);
    connect(powerTray,&PowerTray::showSettingsRequested,this,&MainWindow::show);
    connect(powerTray,&PowerTray::exitRequired,this,&MainWindow::onExitRequired);


    m_settings = g_settings_new("org.ukui.power-manager");
    //screen_settings = g_settings_new("org.ukui.screensaver");
    //process_settings = g_settings_new("org.ukui.process-manager");

    if(!m_settings){
        qDebug() << "Settings对象无效";
        return;
    }
    int value = g_settings_get_int(m_settings,"sleep-computer-ac");
    qDebug() << "读取到的测试值:" << value;


    QWidget *centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);
    QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);//垂直布局管理器
    //mainLayout->addWidget(trayCheckBox);
    searchBox = new QLineEdit(this);
    searchBox->setPlaceholderText(tr("Search"));
    searchBox->setContentsMargins(300,5,300,5);
    mainLayout->addWidget(searchBox);
    mainLayout->setSpacing(0);
    // 新增：用QScrollArea包裹SettingsWidget
    QScrollArea *scrollArea = new QScrollArea(this);
    scrollArea->setWidgetResizable(true);

    settingsWidget = new SettingsWidget(this,m_settings);
    //mainLayout->addWidget(settingsWidget);
    scrollArea->setWidget(settingsWidget);
    mainLayout->addWidget(scrollArea);
    //新增复选框
    QCheckBox *trayCheckBox = new QCheckBox(tr("Show tray icon"),this);
    trayCheckBox->setChecked(false);
    mainLayout->addWidget(trayCheckBox);

    connect(trayCheckBox,&QCheckBox::toggled,powerTray,&PowerTray::setVisible);//
    onShowTrayIcon(trayIconVisible);
    //添加语言菜单
//         languageMenu = menuBar()->addMenu(tr("Language"));
//         chineseAction = new QAction(tr("Chinese"),this);
//         englishAction = new QAction(tr("English"),this);
//         languageMenu->addAction(chineseAction);
//         languageMenu->addAction(englishAction);

//         connect(chineseAction,&QAction::triggered,[this](){
//             qDebug()<<"点击中文按钮";
//             loadLanguage("zh_CN");
//         });
//         connect(englishAction,&QAction::triggered,[this](){
//             qDebug()<<"点击英文按钮";
//             loadLanguage("en_US");
//         });
//         // 加载默认语言
//         QSettings settings;
//         QString lang = settings.value("language", QLocale::system().name()).toString();
//         qDebug()<<"lang:"<<lang;
//         loadLanguage(lang);
}
void MainWindow::loadLanguage(const QString &language){
//移除旧翻译
    qApp->removeTranslator(appTranslator);

    // 加载应用翻译
    QString basePath = "/home/ky/桌面/zhaowei/powersettings/translations/";
    if(appTranslator->load(basePath+language+".qm")) {
          qApp->installTranslator(appTranslator);
          qDebug()<<"加载成功";
    }else{
        qDebug()<<"加载失败";
    }

    // 保存设置
    QSettings().setValue("language", language);
    retranslateUi();
    searchBox->setPlaceholderText(tr("Search"));
}
void MainWindow::retranslateUi(){
    ui->retranslateUi(this);
    languageMenu->setTitle(tr("Language"));      // 更新菜单标题
    chineseAction->setText(tr("Chinese"));      // 更新动作文本
    englishAction->setText(tr("English"));
    if(settingsWidget){
        settingsWidget->retranslateUi();
    }
}
void MainWindow::onShowTrayIcon(bool checked){
    trayIconVisible=checked;
    if(powerTray){
        powerTray->setVisible(checked);
    }
}
void MainWindow::onExitRequired(){
    QApplication::exit();
}
void MainWindow::closeEvent(QCloseEvent *event){
    if(powerTray && powerTray->isVisible()){
        QMessageBox::StandardButton reply;//存储用户的选择
        reply = QMessageBox::question(this,tr("Exit"),tr("Do you want to exit the tray icon as well?"),
                                      QMessageBox::Yes | QMessageBox::No);
        if(reply==QMessageBox::Yes){
            powerTray->setVisible(false);
                    QApplication::quit();
        }else{
            this->hide();
            event->ignore();//阻止关闭
        }

    }else{
        QApplication::quit();
    }
}
MainWindow::~MainWindow()
{
    delete ui;
    if (m_settings) {
            g_object_unref(m_settings);
        }
}

